//
//  HistoryManager.m
//  PFScan
//
//  Created by perfayMini on 2018/10/25.
//  Copyright © 2018 perfayMini. All rights reserved.
//

#import "HistoryManager.h"

@implementation HistoryManager


singleM(HistoryManager)


- (void)saveHistory:(NSString *)hisStr{
    
    NSArray * hislist = [[NSUserDefaults standardUserDefaults] objectForKey:@"History"];
    NSDictionary * hisDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"HistoryCount"];
    
    NSMutableArray * hisTempArray = [[NSMutableArray alloc] init];
    NSMutableDictionary * hisTempCountDic = [[NSMutableDictionary alloc] init];


    if(!hislist){
        [hisTempArray addObject:hisStr];
        [hisTempCountDic setObject:@(1) forKey:hisStr];
        
    }else{
        if([hislist indexOfObject:hisStr] == NSNotFound){
            [hisTempArray addObjectsFromArray:hislist];
            [hisTempArray addObject:hisStr];
            [hisTempCountDic setDictionary:hisDic];
            [hisTempCountDic setObject:@(1) forKey:hisStr];
        }else{
            [hisTempArray addObjectsFromArray:hislist];
            [hisTempCountDic setDictionary:hisDic];
            int count = [self historyCountWithHistory:hisStr];
            count ++;
            [hisTempCountDic setObject:@(count) forKey:hisStr];
        }
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:hisTempArray forKey:@"History"];
    [[NSUserDefaults standardUserDefaults] setObject:hisTempCountDic forKey:@"HistoryCount"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (NSArray *)histories{
    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"History"]){
        return @[];
    }
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"History"];
}


- (int)historyCountWithHistory:(NSString *)his{
    if([[self histories] indexOfObject:his] == NSNotFound){
        return 1;
    }else{
        NSDictionary * countDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"HistoryCount"];
        return [countDic[his] intValue];
    }
}

@end
